﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        private const string _fileUploadPath = "~/FileUploads";

        public ActionResult Index()
        {
            var path = Server.MapPath(_fileUploadPath);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            var uploadedFiles = new DirectoryInfo(path).GetFiles("*").AsEnumerable();
            return View(uploadedFiles);
        }

        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            SaveFile(file);
            return RedirectToAction("Index");
        }

        public ActionResult UploadFiles()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
                SaveFile(file);

            return RedirectToAction("Index");
        }

        private void SaveFile(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                var filename = Path.GetFileNameWithoutExtension(file.FileName) ?? "";
                var fileExtention = Path.GetExtension(file.FileName) ?? "file";
                filename = filename + "_" + DateTime.Now.ToString("dd_MM_yyy_HH_MM_ss_ff") + fileExtention;

                var path = Path.Combine(Server.MapPath(_fileUploadPath), filename);
                file.SaveAs(path);
            }
        }
    }
}
